package top.xbaoziplus.company.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import top.xbaoziplus.company.common.CommonPage;
import top.xbaoziplus.company.common.CustomException;
import top.xbaoziplus.company.common.Result;
import top.xbaoziplus.company.empty.Staff;
import top.xbaoziplus.company.empty.User;
import top.xbaoziplus.company.empty.UserAccount;
import top.xbaoziplus.company.empty.UserInfo;
import top.xbaoziplus.company.service.StaffService;
import top.xbaoziplus.company.service.UserAccountService;
import top.xbaoziplus.company.service.UserInfoService;
import top.xbaoziplus.company.service.UserService;
import top.xbaoziplus.company.utils.MD5Util;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author xBaozi
 * @version 1.0
 * @classname UserController
 * @description 用户控制器
 * @date 2022/6/29 9:26
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户控制器")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserAccountService accountService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private StaffService staffService;


    /**
     * @description 用户登录接口
     * @author xBaozi
     * @date 8:26 2022/7/4
     * @param user  用户对象，存放账号密码
     **/
    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Result<UserInfo> login(@ApiParam("用户对象，存账号密码") @RequestBody User user, @ApiIgnore HttpSession session) {
        log.info("用户登录信息为{}", user);
        // 对用户密码进行加盐双md5加密
        String password = user.getPassword();
        user.setPassword(MD5Util.saltEncode(password));
        // 验证员工是否存在
        if (ObjectUtils.isEmpty(user.getJobId()) || !userService.isExist(user.getJobId())) {
            throw new CustomException("账号不存在，请先前往注册");
        }
        UserInfo info = userService.findByJobIdAndPassword(user.getJobId(), user.getPassword());
        log.info("登录成功，登录人信息为{}", info);
        session.setAttribute("user", info);
        return Result.success(info, "登录成功");
    }

    /**
     * @description 退出登录
     * @author xBaozi
     * @date 8:25 2022/7/4
     **/
    @ApiOperation("用户登出接口")
    @PostMapping("/logout")
    public Result<String> logout(@ApiIgnore HttpSession session) {
        UserInfo user = (UserInfo)session.getAttribute("user");
        log.info("用户{}已退出登录", user.getName());
        session.removeAttribute("user");
        return Result.success("登出成功");
    }

    /**
     * @description 登录进去查看
     * @author xBaozi
     * @date 18:10 2022/7/4
     **/
    @ApiOperation("登录进来获取用户信息")
    @GetMapping("/getInfo")
    public Result<UserInfo> getUserInfo(HttpSession session) {
        UserInfo user = (UserInfo) session.getAttribute("user");
        log.info("登录的个人信息为：=》 {}", user);
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getJobId, user.getJobId());
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new CustomException("该用户不存在");
        }
        if (userInfo.getAcStatus().equals(User.DESTROYED) || userInfo.getAcStatus().equals(Staff.OUT_WORK)) {
            throw new CustomException("该账号状态异常");
        }
        return Result.success(userInfo, "用户查询成功");
    }

    /**
     * @description 获取用户信息接口
     * @author xBaozi
     * @date 18:10 2022/7/4
     **/
    @ApiOperation("通过工号获取用户信息")
    @GetMapping("/{id}")
    public Result<UserInfo> getUser(@PathVariable("id") Long jodId) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getJobId, jodId);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new CustomException("该用户不存在");
        }
        if (userInfo.getAcStatus().equals(User.DESTROYED) || userInfo.getAcStatus().equals(Staff.OUT_WORK)) {
            throw new CustomException("该账号状态异常");
        }
        return Result.success(userInfo, "用户查询成功");
    }


    /**
     * @description 用户注册接口
     * @author xBaozi
     * @date 14:48 2022/7/4
     **/
    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public  Result<UserInfo> register(@ApiParam("用户注册信息") @RequestBody UserInfo userInfo)   {
        log.info("需要注册的用户信息为{}", userInfo);
        // 通过工号获取员工信息
        UserInfo info = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getJobId, userInfo.getJobId()));
        // 判断员工是否存在
        if (ObjectUtils.isEmpty(info)) {
            throw new CustomException("请输入正确的工号");
        }
        // 判断用户是否存在
        if (StringUtils.isNoneBlank(info.getPassword())) {
            throw new CustomException("该账号已存在，请前往登录");
        }
        // 判断员工姓名和手机号是否正确
        Staff staffInDb = staffService.getById(info.getJobId());
        if (!staffInDb.getName().equals(userInfo.getName())
                || !staffInDb.getTelephone().equals(userInfo.getTelephone())) {
            throw new CustomException("请输入正确的信息数据");
        }
        // 对用户密码进行加盐
        String password = userInfo.getPassword();
        userInfo.setPassword(MD5Util.saltEncode(password));
        // 将注册信息复制到User对象中
        User user = new User();
        BeanUtils.copyProperties(userInfo, user);
        userService.save(user);
        return Result.success(userInfo, "用户" + userInfo.getName() + "注册成功");
    }


    /**
     * 用户修改用户密码
     * @param newPassword 新密码
     * @param oldPassword 旧密码
     * @return
     */
    @ApiOperation("用户修改个人密码")
    @PostMapping("/modifyPassword/{oldPassword}/{newPassword}")
    public Result modifyPassword(@PathVariable @ApiParam("新密码") String newPassword,
                                 @PathVariable @ApiParam("旧密码") String oldPassword,
                                 HttpSession session){
        UserInfo user = (UserInfo) session.getAttribute("user");
        log.info("已经登录的用户：{} ", user);
        log.info("检查密码旧密码是否一样");
        String s = MD5Util.saltEncode(oldPassword);
        log.info("用户旧密码： {}", s);
        if (!user.getPassword().equals(s)){
            return Result.fail("旧密码输入不正确");
        }
        User user1 = new User();
        user1.setPassword(MD5Util.saltEncode(newPassword));
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getJobId, user.getJobId());
        boolean update = userService.update(user1, queryWrapper);
        if (update){
            return Result.success("修改密码成功");
        }
        return Result.fail("修改密码失败");
    }

    @ApiOperation("管理员修改用户密码")
    @PostMapping("/admin/modifyPassword/{userId}/{password}")
    public Result modifyPassword(@PathVariable @ApiParam("用户工号") Long userId,
                                 @PathVariable @ApiParam("新密码") String password){
        log.info("管理员修改员工密码");
        String saltEncode = MD5Util.saltEncode(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getJobId, userId);
        User user = new User();
        user.setPassword(saltEncode);
        boolean update = userService.update(user, queryWrapper);
        if (update){
            return Result.success("重置密码成功");
        }else {
            return Result.fail("重置密码失败");
        }
    }

    @ApiOperation("管理员端展示员工账号列表:0表示展示正常账号，1表示展示删除账号")
    @PostMapping("/admin/userList/{type}")
    public Result userList(@RequestBody @ApiParam("传模糊查询数据/页码/一页总数量过来") CommonPage commonPage,
                           @PathVariable @ApiParam("显示类型") Integer type){
        log.info("分页展示员工账号信息===》前端传来的数据 ===》{}", commonPage);
        if (ObjectUtils.isEmpty(commonPage.getCurrentPage())
                &&!ObjectUtils.isEmpty(commonPage.getPageSize())){
            return Result.fail("参数错误");
        }
        return userService.getAllPage(commonPage, type);
    }

    @ApiOperation("管理员对员工账号进行删除恢复操作:0表示恢复,1表示删除")
    @PostMapping("/admin/operation/{jobId}/{type}")
    public Result remove(@PathVariable @ApiParam("员工工号") Long jobId,
                         @PathVariable @ApiParam("操作类型") Integer type){
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getJobId, jobId);
        UserAccount userAccount = new UserAccount();
        userAccount.setStatus(type);
        boolean update = accountService.update(userAccount, queryWrapper);
        if (update){
            return Result.success("操作成功");
        }else {
            return Result.fail("操作失败");
        }
    }


}
